#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户管理相关路由
"""
import csv
import io
from datetime import datetime
from fastapi import APIRouter, Request, Form, File, UploadFile, HTTPException
from fastapi.responses import Response
from fastapi.templating import Jinja2Templates

from ..database import get_db_connection, row_to_dict, rows_to_dict_list
from ..utils.config import config
from ..utils.security import hash_password
from ..auth.session import verify_admin, verify_user

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/api/users")
async def get_users(request: Request):
    """获取用户列表API"""
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    
    conn = get_db_connection()
    users = conn.execute("""
        SELECT id, username, phone, email, role, is_active, created_at, updated_at 
        FROM users ORDER BY created_at DESC
    """).fetchall()
    conn.close()
    
    return {"users": rows_to_dict_list(users)}


@router.get("/api/users/{user_id}")
async def get_user(request: Request, user_id: int):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """获取单个用户信息API"""
    conn = get_db_connection()
    user = conn.execute("""
        SELECT id, username, phone, email, role, is_active, created_at, updated_at 
        FROM users WHERE id = ?
    """, (user_id,)).fetchone()
    conn.close()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return {"user": row_to_dict(user)}


@router.put("/api/users/{user_id}")
async def update_user(
    request: Request,
    user_id: int,
    username: str = Form(...),
    phone: str = Form(""),
    email: str = Form(""),
    role: str = Form(...),
    password: str = Form("")
):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """更新用户信息API"""
    conn = get_db_connection()
    
    # 检查用户是否存在
    existing_user = conn.execute("SELECT id FROM users WHERE id = ?", (user_id,)).fetchone()
    if not existing_user:
        conn.close()
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查用户名是否已被其他用户使用
    if conn.execute("SELECT id FROM users WHERE username = ? AND id != ?", (username, user_id)).fetchone():
        conn.close()
        raise HTTPException(status_code=400, detail="用户名已被使用")
    
    # 准备更新语句
    update_data = {}
    update_data["username"] = username
    update_data["phone"] = phone
    update_data["email"] = email
    update_data["role"] = role
    update_data["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    if password:
        update_data["password_hash"] = hash_password(password)
    
    # 构建更新SQL
    set_clause = ", ".join([f"{k} = ?" for k in update_data.keys()])
    values = list(update_data.values()) + [user_id]
    
    cursor = conn.cursor()
    cursor.execute(f"""
        UPDATE users
        SET {set_clause}
        WHERE id = ?
    """, values)
    
    conn.commit()
    conn.close()
    
    
    
    return {"message": "用户信息更新成功"}


@router.patch("/api/users/{user_id}/status")
async def toggle_user_status(request: Request, user_id: int, is_active: bool = Form(...)):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """切换用户激活状态API"""
    conn = get_db_connection()
    
    # 检查用户是否存在
    existing_user = conn.execute("SELECT id FROM users WHERE id = ?", (user_id,)).fetchone()
    if not existing_user:
        conn.close()
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新用户状态
    cursor = conn.cursor()
    cursor.execute("""
        UPDATE users
        SET is_active = ?, updated_at = ?
        WHERE id = ?
    """, (is_active, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user_id))
    
    conn.commit()
    conn.close()
    
    
    return {"message": f"用户已{status_text}"}


@router.delete("/api/users/{user_id}")
async def delete_user(request: Request, user_id: int):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """删除用户API"""
    conn = get_db_connection()
    
    # 检查用户是否存在
    existing_user = conn.execute("SELECT id FROM users WHERE id = ?", (user_id,)).fetchone()
    if not existing_user:
        conn.close()
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 删除用户（级联删除相关数据）
    cursor = conn.cursor()
    cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))
    conn.commit()
    conn.close()
    
    return {"message": "用户删除成功"}


@router.post("/api/users")
async def create_user(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    phone: str = Form(""),
    email: str = Form(""),
    role: str = Form("user")
):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """创建用户API"""
    conn = get_db_connection()
    
    # 检查用户名是否已存在
    existing_user = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
    if existing_user:
        conn.close()
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 创建新用户
    password_hash = hash_password(password)
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO users (username, password_hash, phone, email, role)
        VALUES (?, ?, ?, ?, ?)
    """, (username, password_hash, phone, email, role))
    
    user_id = cursor.lastrowid
    conn.commit()
    conn.close()
    
    
    
    return {"message": "用户创建成功", "user_id": user_id}


@router.delete("/api/users/batch")
async def batch_delete_users(request: Request, user_ids: str = Form(...)):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """批量删除用户API"""
    try:
        # 解析用户ID列表
        import json
        user_id_list = json.loads(user_ids)
        
        if not user_id_list:
            raise HTTPException(status_code=400, detail="未选择要删除的用户")
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 批量删除用户
        placeholders = ",".join(["?" for _ in user_id_list])
        cursor.execute(f"DELETE FROM users WHERE id IN ({placeholders})", user_id_list)
        
        deleted_count = cursor.rowcount
        conn.commit()
        conn.close()
        
        return {"message": f"成功删除 {deleted_count} 个用户"}
        
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="用户ID格式错误")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")


@router.post("/api/import/users")
async def import_users(
    request: Request,
    file: UploadFile = File(...),
    skip_duplicates: bool = Form(False)
):
    """导入用户API"""
    verify_admin(request)
    
    if not file.filename.endswith(('.csv', '.xlsx', '.xls')):
        raise HTTPException(status_code=400, detail="只支持CSV、Excel文件格式")
    
    try:
        content = await file.read()
        
        # 解析文件内容
        if file.filename.endswith('.csv'):
            # CSV文件处理
            content_str = content.decode('utf-8-sig')  # 处理BOM
            csv_reader = csv.DictReader(io.StringIO(content_str))
            data_rows = list(csv_reader)
        else:
            # Excel文件处理
            import pandas as pd
            df = pd.read_excel(io.BytesIO(content))
            data_rows = df.to_dict('records')
        
        if not data_rows:
            raise HTTPException(status_code=400, detail="文件为空或格式错误")
        
        # 验证必需的列
        required_columns = ['username', 'password']
        first_row = data_rows[0]
        missing_columns = [col for col in required_columns if col not in first_row]
        if missing_columns:
            raise HTTPException(status_code=400, detail=f"缺少必需的列: {', '.join(missing_columns)}")
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        success_count = 0
        skipped_count = 0
        error_count = 0
        errors = []
        
        for row_index, row in enumerate(data_rows, start=2):  # 从第2行开始（第1行是标题）
            try:
                username = str(row.get('username', '')).strip()
                password = str(row.get('password', '')).strip()
                phone = str(row.get('phone', '')).strip()
                email = str(row.get('email', '')).strip()
                
                if not username or not password:
                    errors.append({
                        "row": row_index,
                        "message": "用户名和密码不能为空"
                    })
                    error_count += 1
                    continue
                
                # 检查用户名是否已存在
                existing_user = conn.execute(
                    "SELECT id FROM users WHERE username = ?", (username,)
                ).fetchone()
                
                if existing_user:
                    if skip_duplicates:
                        skipped_count += 1
                        continue
                    else:
                        errors.append({
                            "row": row_index,
                            "message": f"用户名 '{username}' 已存在"
                        })
                        error_count += 1
                        continue
                
                # 创建用户
                password_hash = hash_password(password)
                cursor.execute("""
                    INSERT INTO users (username, password_hash, phone, email)
                    VALUES (?, ?, ?, ?)
                """, (username, password_hash, phone, email))
                
                success_count += 1
                
            except Exception as e:
                errors.append({
                    "row": row_index,
                    "message": f"处理失败: {str(e)}"
                })
                error_count += 1
        
        conn.commit()
        conn.close()
        
        return {
            "message": "用户导入完成",
            "total_count": len(data_rows),
            "success_count": success_count,
            "skipped_count": skipped_count,
            "error_count": error_count,
            "errors": errors[:10]  # 最多返回10个错误
        }
        
    except UnicodeDecodeError:
        raise HTTPException(status_code=400, detail="文件编码错误，请使用UTF-8编码")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")


@router.get("/api/export/users")
async def export_users(request: Request):
    """导出用户API"""
    verify_admin(request)
    
    conn = get_db_connection()
    users = conn.execute("""
        SELECT username, phone, email, role, is_active, created_at, updated_at
        FROM users
        ORDER BY created_at DESC
    """).fetchall()
    conn.close()
    
    # 生成CSV内容
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入标题行
    writer.writerow(['用户名', '手机号', '邮箱', '角色', '状态', '创建时间', '更新时间'])
    
    # 写入数据行
    for user in users:
        writer.writerow([
            user['username'],
            user['phone'] or '',
            user['email'] or '',
            user['role'],
            '启用' if user['is_active'] else '禁用',
            user['created_at'],
            user['updated_at']
        ])
    
    csv_content = output.getvalue()
    output.close()
    
    # 返回CSV文件
    response = Response(
        content=csv_content.encode('utf-8-sig'),  # 添加BOM以支持Excel正确显示中文
        media_type='text/csv',
        headers={
            'Content-Disposition': f'attachment; filename="users_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv"'
        }
    )
    
    return response


@router.get("/profile")
async def profile(request: Request):
    try:
        user = verify_user(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """个人中心页面"""
    conn = get_db_connection()
    
    # 获取用户信息
    user_info = conn.execute("SELECT * FROM users WHERE id = ?", (user['id'],)).fetchone()
    
    # 获取统计数据
    password_count = conn.execute("SELECT COUNT(*) as count FROM passwords WHERE user_id = ?", (user['id'],)).fetchone()['count']
    share_count = conn.execute("SELECT COUNT(*) as count FROM password_shares ps JOIN passwords p ON ps.password_id = p.id WHERE p.user_id = ?", (user['id'],)).fetchone()['count']
    
    # 计算注册天数
    from datetime import datetime
    created_at = datetime.fromisoformat(user_info['created_at'])
    days_since_registration = (datetime.now() - created_at).days
    
    conn.close()
    
    return templates.TemplateResponse("profile.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_short'),
        "user": user_info,
        "password_count": password_count,
        "share_count": share_count,
        "days_since_registration": days_since_registration
    })


@router.get("/api/profile/stats")
async def get_profile_stats(request: Request):
    try:
        user = verify_user(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    
    conn = get_db_connection()
    
    # 获取统计数据
    password_count = conn.execute("SELECT COUNT(*) as count FROM passwords WHERE user_id = ?", (user['id'],)).fetchone()['count']
    share_count = conn.execute("SELECT COUNT(*) as count FROM password_shares ps JOIN passwords p ON ps.password_id = p.id WHERE p.user_id = ?", (user['id'],)).fetchone()['count']
    
    # 计算注册天数
    from datetime import datetime
    user_info = conn.execute("SELECT created_at FROM users WHERE id = ?", (user['id'],)).fetchone()
    created_at = datetime.fromisoformat(user_info['created_at'])
    days_since_registration = (datetime.now() - created_at).days
    
    conn.close()
    
    return {
        "password_count": password_count,
        "share_count": share_count,
        "login_days": days_since_registration
    }


@router.put("/api/profile")
async def update_profile(
    request: Request,
    phone: str = Form(""),
    email: str = Form("")
):
    try:
        user = verify_user(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("""
        UPDATE users
        SET phone = ?, email = ?, updated_at = ?
        WHERE id = ?
    """, (phone, email, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user['id']))
    
    conn.commit()
    conn.close()
    
    
    
    return {"message": "个人信息更新成功"}


@router.put("/api/profile/password")
async def update_profile_password(
    request: Request,
    current_password: str = Form(...),
    new_password: str = Form(...),
    confirm_password: str = Form(...)
):
    try:
        user = verify_user(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    
    if new_password != confirm_password:
        raise HTTPException(status_code=400, detail="两次输入的新密码不一致")
    
    conn = get_db_connection()
    
    # 验证当前密码
    user_info = conn.execute("SELECT password_hash FROM users WHERE id = ?", (user['id'],)).fetchone()
    if user_info['password_hash'] != hash_password(current_password):
        conn.close()
        raise HTTPException(status_code=400, detail="当前密码错误")
    
    # 更新密码
    new_password_hash = hash_password(new_password)
    cursor = conn.cursor()
    cursor.execute("""
        UPDATE users
        SET password_hash = ?, updated_at = ?
        WHERE id = ?
    """, (new_password_hash, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user['id']))
    
    conn.commit()
    conn.close()
    
    
    
    return {"message": "密码修改成功"}